package com.ms.p2p.plugin.validation;


import com.ms.common.utils.AppContext;
import com.ms.common.utils.WebErrors;

import com.ms.p2p.Constants;
import com.ms.p2p.plugin.AutoRegisterPlugin;
import com.ms.p2p.plugin.validation.annotation.TokenValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/*
 * 权限验证
 * 
 * **/
public class TokenValidate extends AutoRegisterPlugin implements IValidate {


	@Override
	public String getType() {
		return "vallidate";
	}

	@Override
	public String getId() {
		return "tokenValidate";
	}

	@Override
	public String getName() {
		return "重复提交检验";
	}

	@Override
	public String getVersion() {
		return "1.0.0";
	}

	@Override
	public String getAuthor() {
		return "daimajia";
	}

	@Override
	public void perform(Object... params) {

	}

	@Override
	public void register() {

	}

	@Override
	public WebErrors validate(HttpServletRequest request, WebErrors errors,
							  Validations validations, Map<String, String> decodedUriVariables) {
		TokenValidator[] validators = validations.token();
		if(errors.hasErrors()){
			return errors;
		}else {
			if (validators.length > 0) {
				String token = request.getParameter("token");
				if (!StringUtils.isNotBlank(token)) {
					errors.addErrorString("请不要重复提交,请刷新当前页面后再操作");

				} else {
					if (!StringUtils.isNotBlank(AppContext.getSessionAttr(Constants.VALIDATE_TOKEN_KEY) + "") || !token.equals(AppContext.getSessionAttr(Constants.VALIDATE_TOKEN_KEY))) {
						errors.addErrorString("请不要重复提交,请刷新当前页面后再操作");
					}
					if(StringUtils.isNotBlank(AppContext.getSessionAttr(Constants.VALIDATE_TOKEN_KEY) + "")&&token.equals(AppContext.getSessionAttr(Constants.VALIDATE_TOKEN_KEY))){
						AppContext.getRequest().getSession().removeAttribute(Constants.VALIDATE_TOKEN_KEY);
					}

				}
			}
			return errors;
		}
	}
}
